package com.zjy.weather.fragment

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v4.content.ContextCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.alibaba.fastjson.JSONObject
import com.amap.api.location.AMapLocation
import com.zjy.weather.R
import com.zjy.weather.TAG
import com.zjy.weather.adapter.WeatherAdapter
import com.zjy.weather.base.RequestCallback
import com.zjy.weather.bean.HeWeather
import com.zjy.weather.bean.Weather
import com.zjy.weather.data.WeatherDataManager
import com.zjy.weather.util.DiskStringCache
import com.zjy.weather.util.location.LocationExecutor
import com.zjy.weather.util.location.LocationListener

/**
 * Created by zhongjy on 2017/11/2.
 * Copyright (C) 2017 zhongjy. All rights reserved.
 */
class WeatherFragement : Fragment() {
    private val ACCESS_COARSE_LOCATION_REQUEST_CODE = 0;
    private var mLocationExecutor: LocationExecutor? = null
    private var location: String? = null
    private lateinit var mRecyleView: RecyclerView
    private lateinit var mAdapter: WeatherAdapter
    private lateinit var mWeather: Weather
    private lateinit var mSwipeRefreshLayout: SwipeRefreshLayout

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater?.inflate(R.layout.fragment_weather, container, false)
        view?.let {
            initView(view)
            initData()
        }
        return view;
    }

    fun initView(root: View) {
        mRecyleView = root.findViewById(R.id.weather_rv) as RecyclerView
        mSwipeRefreshLayout = root.findViewById(R.id.reresh_layout) as SwipeRefreshLayout

    }

    fun initData() {
        mAdapter = WeatherAdapter(activity, null)
        mRecyleView.layoutManager = LinearLayoutManager(activity)
        mRecyleView.adapter = mAdapter
        mSwipeRefreshLayout.setOnRefreshListener(object : SwipeRefreshLayout.OnRefreshListener {
            override fun onRefresh() {
                location?.let {
                    getData(it)
                } ?: let {
                    mSwipeRefreshLayout.isRefreshing = false
                }
            }
        }
        )

        location = DiskStringCache.getString(activity, "location")
        location?.let { getData(it) } ?: let { checkPermission() }
    }


    /**
     * 获取天气数据
     */
    fun getData(location: String) {
        WeatherDataManager.getWeather(activity, location, object : RequestCallback {
            override fun onError() {
                mSwipeRefreshLayout.isRefreshing = false
            }

            override fun onSuccess(response: String?) {
                mSwipeRefreshLayout.isRefreshing = false
                response?.let {
                    var res = JSONObject.parseObject(response, HeWeather::class.javaObjectType) as HeWeather
                    res?.let {
                        res.weather?.let {
                            if (it.size > 0) {
                                mWeather = it.get(0)
                                mAdapter?.setData(mWeather)
                            }
                        }
                    }
                }
            }
        })
    }


    /**
     * 权限请求回调
     */
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == ACCESS_COARSE_LOCATION_REQUEST_CODE) {
            startlocate()
        }
    }

    /**
     * 检查定位权限
     */
    fun checkPermission() {
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION),
                    ACCESS_COARSE_LOCATION_REQUEST_CODE);
        } else {
            startlocate()
        }
    }


    /**
     * 开始定位
     */
    fun startlocate() {
        if (mLocationExecutor == null) {
            mLocationExecutor = LocationExecutor(activity, object : LocationListener {
                override fun onLocationFailed() {

                }

                override fun onLocationSuccess(city: AMapLocation) {

                    dealLocationResult(city)
                }
            })
        }
        mLocationExecutor?.executeLocation()
    }

    /**
     * 处理定位结果
     */
    fun dealLocationResult(city: AMapLocation) {
        Log.e(com.zjy.weather.TAG, city.toStr());
        var locationNow = city?.district ?: (city?.city)
        locationNow?.let {
            if (location.isNullOrEmpty() || !it.equals(location)) {
                DiskStringCache.putString(activity, "location", it)
                getData(it)
            }
        }
    }

}